package com.xyh.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xyh.authserver.feign.MemberFeignService;
import com.xyh.common.utils.HttpUtils;
import com.xyh.common.utils.R;
import com.xyh.common.vo.MemberRespVo;
import com.xyh.common.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("client_id","609074451");
        map.put("client_secret","8eb9f932ce162ea80b2e2f7550d5e9a1");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //1.根据code码换取access token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        //处理
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了access token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道当前是哪个社交用户
            //1)当前用户如果是第一次进网站，自动注册进来（为当前用户生成一个当前会员信息账号）
            //登陆或者注册这个社交用户
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode() == 0){
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute("loginUser",data);
//                new Cookie("JSESSION").
//                servletResponse.addCookie();
                //登陆成功跳回首页
                return "redirect:http://gulimall.com";
            }else {
                //失败
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            //失败
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
